<template>
  <div></div>
</template>
<script>
import { toolbars } from '@/core/const'
// import { haloEditor } from 'halo-editor'
// import 'halo-editor/dist/css/index.css'
import Vditor from 'vditor'
import 'vditor/src/assets/scss/index.scss'
import apiClient from '@/utils/api-client'
import { buildPath } from '@/utils/api-client'
import store from '@/store'

export default {
  name: 'MarkdownEditor',
  components: {},
  props: {
    originalContent: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      toolbars,
      originalContentData: '',
      contentEditor: null
    }
  },
  mounted() {
    const token = store.getters.token
    this.contentEditor = new Vditor(this.$el, {
      cache: { enable: false },
      toolbarConfig: { pin: true },
      minHeight: 500,
      after: () => {
        this.contentEditor.setValue(this.originalContent)
      },
      upload: {
        url: apiClient.client.requestConfigBuilder.baseUrl + buildPath({ endpointName: 'attachments/uploads' }),
        setHeaders: () => {
          return { 'Admin-Authorization': token.access_token }
        },
        fieldName: 'files',
        format: ($files, responseText) => {
          const result = JSON.parse(responseText)
          const ret = {
            msg: '',
            code: 0,
            data: {
              succMap: {}
            }
          }
          for (let index = 0; index < $files.length; index++) {
            ret.data.succMap[$files[index].name] = result.data[index].path
          }
          return JSON.stringify(ret)
        }
      }
    })
  },
  watch: {
    originalContent(val) {
      this.originalContentData = val
    },
    originalContentData(val) {
      //this.$emit('onContentChange', val)
      if (this.contentEditor) {
        this.contentEditor.setValue(val)
      }
    }
  },
  methods: {
    getContent() {
      return this.contentEditor.getValue()
    },
    handleAttachmentUpload(pos, $file) {
      const formdata = new FormData()
      formdata.append('file', $file)
      apiClient.attachment.upload(formdata).then(response => {
        const responseObject = response.data
        const HaloEditor = this.$refs.md
        HaloEditor.$img2Url(pos, encodeURI(responseObject.path))
      })
    },
    handleSaveDraft() {
      this.$emit('onSaveDraft')
    }
  }
}
</script>
